package com.link2room.blaster.facade.impl;

import com.link2room.aeriabots.dto.param.base.WxComponentParamDto;
import com.link2room.blaster.common.FreemarkerUtil;
import com.link2room.blaster.constant.MsgConstant;
import com.link2room.blaster.dto.innerUse.MsgSendParamDto;
import com.link2room.blaster.dto.result.wx.WxCustomNews;
import com.link2room.blaster.entity.MsgSendLogEntity;
import com.link2room.blaster.entity.MsgTemplate;
import com.link2room.blaster.feign.aeriabots.WxOfiiceialAccountsTokenFeignService;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.JacksonUtil;
import com.link2room.common.util.LogUtil;
import com.link2room.common.util.StringUtil;
import com.tencent.client.OfficialAccountClient;
import com.tencent.protocol.ErroBaseReqData;
import com.tencent.protocol.officialAccount.CustomSendProtocol;
import com.tencent.protocol.officialAccount.message.template.send.TemplateSendResDate;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Nakisa on 2016/11/9.
 */
public class BaseFacadeImpl {
    @Resource
    private ICommonService commonServiceSupport;
    @Autowired
    private WxOfiiceialAccountsTokenFeignService wxOfiiceialAccountsTokenFeignService;
    /**
     * 查找消息模板
     * @param lhotelGorupCode
     * @param lhotelCode
     * @param channel
     * @param templateCode
     * @return
     * @throws Exception
     */
    protected MsgTemplate findTemplate(String lhotelGorupCode , String lhotelCode , String channel, String templateCode) throws Exception {
        MsgTemplate s = new MsgTemplate();
        s.setLhotelGroupCode(lhotelGorupCode);
        s.setLhotelCode(lhotelCode);
        s.setChannel(channel);
        s.setCode(templateCode);
        MsgTemplate res = commonServiceSupport.findOneEQ(MsgTemplate.class, s);
        if(res == null){
            LogUtil.logger.warn("No template:"+lhotelGorupCode+" "+channel+" "+templateCode);
        }
        return res;
    }

    /**
     * 查询hotel微信公众号相关信息
     * @param lhotelGroupCode
     * @param lhotelCode
     * @return
     * @throws Exception
     */
    protected String getOfficialAccountsToken(String lhotelGroupCode,String lhotelCode) throws Exception {
        WxComponentParamDto paramDto = new WxComponentParamDto();
        paramDto.setLhotelGroupCode(lhotelGroupCode);
        paramDto.setLhotelCode(lhotelCode);
        return wxOfiiceialAccountsTokenFeignService.getOfficialAccountsToken(paramDto.paramToMap()).getResultInfo();
    }


    /**
     * 记录发送的消息
     * @param res
     * @param msg
     * @throws Exception
     */
    protected void logWxTemplateMsg(String lhotelGroupCode , String hotelCode , TemplateSendResDate res, String msg) throws Exception {
        MsgSendLogEntity log = new MsgSendLogEntity();
        log.setLhotelCode(lhotelGroupCode);
        log.setLhotelGroupCode(hotelCode);
        if(res.getMsgid()!=null){
            log.setMsgId(res.getMsgid().toString());
        }
        log.setErrMsg(res.getErrmsg());
        log.setMsg(msg);
        log.setErrCode(res.getErrcode());
        commonServiceSupport.save(log);
    }

    /**
     * 记录客服消息发送
     * @param lhotelGroupCode
     * @param channel
     * @param temlpateCode
     * @param msg
     * @param errorCode
     * @param errorMsg
     * @throws Exception
     */
    protected void logWxCustomMsg(String lhotelGroupCode , String channel ,String temlpateCode , String msg ,String errorCode,String errorMsg) throws Exception {
        MsgSendLogEntity log = new MsgSendLogEntity();
        log.setLhotelCode(lhotelGroupCode);
        log.setTemplateCode(temlpateCode);
        log.setMsg(msg);
        log.setChannel(channel);
        log.setErrCode(errorCode);
        log.setErrMsg(errorMsg);
        try{
            commonServiceSupport.save(log);
        }catch (Exception e){
            log.setMsg("");
            commonServiceSupport.save(log);
        }
    }

    protected void assertStrParam(String str,String errorMsg){
        if(StringUtil.isBlank(str)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(),errorMsg, BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
    }

    /**
     * 客服消息发送
     * @param lhotelGroupCode
     * @param template
     * @param data
     * @param openid
     * @throws Exception
     */
    private void customSend(String lhotelGroupCode , MsgTemplate template, Map data, String openid) throws Exception {
        String str = FreemarkerUtil.getMsg(template,data);
        WxCustomNews wxNews =  JacksonUtil.jsonToBean(str, WxCustomNews.class);
        String token = this.getOfficialAccountsToken(lhotelGroupCode,null);
        CustomSendProtocol cs = new CustomSendProtocol();
        cs.setTouser(wxNews.getOpenid());
        cs.setMsgtype("news");
        CustomSendProtocol.News news = new CustomSendProtocol.News();
        CustomSendProtocol.Articles article = new CustomSendProtocol.Articles();
        article.setUrl(wxNews.getUrl());
        article.setTitle(wxNews.getTitle());
        article.setDescription(wxNews.getDescription());
        List<CustomSendProtocol.Articles> articles = new ArrayList<CustomSendProtocol.Articles>();
        articles.add(article);
        news.setArticles(articles);
        cs.setNews(news);
        OfficialAccountClient.customSend(token, cs);
        //TODO log
    }

    protected void sendConstomMsg(MsgSendParamDto msgSendParamDto) throws Exception {
        String templateCode = msgSendParamDto.getTemplateCode();
        assertStrParam(templateCode,"[templateCode] is null");
        String lhotelGroupCode = msgSendParamDto.getLhotelGroupCode();
        assertStrParam(lhotelGroupCode,"[lhotelGroupCode] is null");
        MsgTemplate template = findTemplate(lhotelGroupCode, null, MsgConstant.CHANNEL.WECHA_CUSTOM_SEND, templateCode);
        if(template == null){
            return;
        }
        Map data = (Map) msgSendParamDto.getData();
        String str = FreemarkerUtil.getMsg(template,data);
        String openid = (String) data.get("openid");
        WxCustomNews cnews = JacksonUtil.jsonToBean(str, WxCustomNews.class);
        CustomSendProtocol cs = new CustomSendProtocol();
        CustomSendProtocol.News news = new CustomSendProtocol.News();
        CustomSendProtocol.Articles article = new CustomSendProtocol.Articles();
        cs.setTouser(openid);
        cs.setMsgtype("news");
        if(StringUtil.isNotBlank(cnews.getUrl())){
            article.setUrl(cnews.getUrl());
        }
        if(StringUtil.isNotBlank(cnews.getTitle())){
            article.setTitle(cnews.getTitle());
        }
        if(StringUtil.isNotBlank(cnews.getDescription())){
            article.setDescription(cnews.getDescription());
        }
        if(StringUtil.isNotBlank(cnews.getPicurl())){
            article.setPicurl(cnews.getPicurl());
        }
        List<CustomSendProtocol.Articles> articles = new ArrayList<CustomSendProtocol.Articles>();
        articles.add(article);
        news.setArticles(articles);
        cs.setNews(news);
        String token = this.getOfficialAccountsToken(lhotelGroupCode, null);
        ErroBaseReqData res = OfficialAccountClient.customSend(token, cs);
        if(res != null){
            logWxCustomMsg(lhotelGroupCode,template.getChannel(),template.getCode(),JacksonUtil.beanToJson(cs),res.getErrcode(),res.getErrmsg());
        }else{
            res = new ErroBaseReqData();
            res.setErrcode("-1");
            res.setErrmsg("wx SDK response null");
            logWxCustomMsg(lhotelGroupCode,template.getChannel(),template.getCode(),JacksonUtil.beanToJson(cs),res.getErrcode(),res.getErrmsg());
        }
    }

}
